package com.xzr.hospitalregister.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.xzr.hospitalregister.R;

import java.util.HashMap;
import java.util.Locale;
import java.util.StringTokenizer;

/**
 * Created by Administrator on 2018/2/1 0001.
 */

public class AndroidTTSDemoThird extends Activity implements TextToSpeech.OnInitListener,TextToSpeech.OnUtteranceCompletedListener{
    private EditText inputText = null;
    private Button speakBtn = null;
    private TextToSpeech mTts;
    private static final String TAG = "TTS Demo";
    private static final String STORE_NAME = "preferenceFile";
//    private static final String loveConfession = "You complete me. You had me at hello, you had me at hello. To the world you maybe one person, but to one person you maybe the world. Please believe me, I was prepared for everything,except you. I love that you are the last person I want to talk to before I go to sleep at night. Love means never having to say you're sorry. So choose me. Marry me. Let me make you happy. ";
private static final String loveConfession = "请张三到一诊室就诊,李四准备就诊,";
    private String[] loveArray;
    private int lastUtterance = -1;
    private HashMap<String, String> params = new HashMap<String, String>();

    private static final int msgKey2 = 5;//////////////////
    public boolean isSelected =true;////////////////
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_androidtts);

        //创建TextToSpeech实例，初始化完成后会调用OnInitListener（第二个参数）的回调函数
        if(isSelected){
        mTts = new TextToSpeech(this,
                this  // TextToSpeech.OnInitListener
        );
    }/////////////
        //////////
        //设置控件
        inputText = (EditText)findViewById(R.id.inputText);
        speakBtn = (Button)findViewById(R.id.speakBtn);

//        inputText.setText(loveConfession);//////////////
        speakBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
//                //处理输入框里的内容
//                StringTokenizer loveTokens = new StringTokenizer(inputText.getText().toString(),",.");
//                int i = 0;
//                loveArray = new String[loveTokens.countTokens()];
//                while(loveTokens.hasMoreTokens())
//                {
//                    loveArray[i++] = loveTokens.nextToken();
//                }
//                //朗读输入框里的内容
//                speakText();
            }
        });
        ///////////
        SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
        lastUtterance = settings.getInt("lastUtterance", -1);
        Log.v(TAG, "the restored lastUtterance is " + lastUtterance);
        Log.v(TAG, "上面保存的值 lastUtterance is " + lastUtterance);
        ////////////
        new TimeThreadjh().start();////////////////////////////////////////////////////////////////////
    }

    @Override
    public void onInit(int status) {
// TODO Auto-generated method stub
        //TTS Engine初始化完成
        if(status == TextToSpeech.SUCCESS)
        {
            int result = mTts.setLanguage(Locale.US);
            //设置发音语言
            if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
            //判断语言是否可用
            {
                Log.v(TAG, "Language is not available");
                speakBtn.setEnabled(false);
            }
            else
            {
                speakBtn.setEnabled(true);
                //设置一个语音片段结束后的回调函数
                mTts.setOnUtteranceCompletedListener(this);
            }
        }
    }

    @Override
    public void onUtteranceCompleted(String utteranceId) {
// TODO Auto-generated method stub
        //一个语音片段结束后的回调函数
        Log.v(TAG, "Get completed message for the utteranceId " + utteranceId);
        //用lastUtterance记录当前结束的语音片段
        lastUtterance = Integer.parseInt(utteranceId);
    }
    private void speakText()
    {
        lastUtterance++;
        if(lastUtterance >= loveArray.length)
        {
            lastUtterance = 0;
        }
        Log.v(TAG, "the begin utterance is " + lastUtterance);
        for(int i = lastUtterance; i < loveArray.length; i++)
        {
            //为每个语音片段都设置一个标记
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, String.valueOf(i));
            mTts.speak(loveArray[i], TextToSpeech.QUEUE_ADD, params);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        //释放TTS的资源
        if(mTts != null)
        {
            mTts.stop();
            mTts.shutdown();
        }
        //保存lastUtterance值
        SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("lastUtterance", lastUtterance);
        editor.commit();
        Log.v(TAG, "the stored lastUtterance is " + lastUtterance);

        super.onDestroy();
    }
    /////////
    public class TimeThreadjh extends Thread {
        @Override
        public void run () {
            do {
                try {
                    Thread.sleep(5000);
                    Message msg = new Message();
                    msg.what = msgKey2;
                    mHandlerjh.sendMessage(msg);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while(true);
        }
    }
    private Handler mHandlerjh = new Handler() {
        @Override
        public void handleMessage (Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey2:
//                    long sysTime = System.currentTimeMillis();
//                    CharSequence sysTimeStr = DateFormat.format("EEEE HH:mm:ss", sysTime);
//                    tv_mTime.setText(sysTimeStr);
//                    //////////
//                    //处理输入框里的内容
//                    StringTokenizer loveTokens = new StringTokenizer(inputText.getText().toString(),",.");
//                    int i = 0;
//                    loveArray = new String[loveTokens.countTokens()];
//                    while(loveTokens.hasMoreTokens())
//                    {
//                        loveArray[i++] = loveTokens.nextToken();
//                    }
//                    //朗读输入框里的内容
//                    speakText();
//                    //////////
//                    SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
//                    lastUtterance = settings.getInt("lastUtterance", -1);
//                    Log.v(TAG, "the restored lastUtterance is " + lastUtterance);
//                    //////////
                    //释放TTS的资源
                    if(isSelected)
                    {
                        //处理输入框里的内容
                        StringTokenizer loveTokens = new StringTokenizer(inputText.getText().toString(),",.");
                        Log.e("TAG","输入框的内容+++++++++"+inputText.getText().toString());
                        int i = 0;
                        loveArray = new String[loveTokens.countTokens()];
                        while(loveTokens.hasMoreTokens())
                        {
                            loveArray[i++] = loveTokens.nextToken();
                        }
                        //朗读输入框里的内容
                        speakText();
                        //////////
                        isSelected =false;
                    }else{
                        if(lastUtterance==0){
                            mTts.stop();
                        }else {
                            isSelected=true;
                        }
                        //////////

//                        mTts.shutdown();
//                        ///////////
//                        //保存lastUtterance值
//                        SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
//                        SharedPreferences.Editor editor = settings.edit();
//                        editor.putInt("lastUtterance", lastUtterance);
//                        editor.commit();
//                        Log.v(TAG, "the stored lastUtterance is " + lastUtterance);
//                        Log.v(TAG, "保存的值 lastUtterance is " + lastUtterance);
//                        isSelected = true;
                        ///////////
                    }
                        /////////


                    break;

                default:
                    break;
            }
        }
    };
    /////////////
}
